import {
  registerUser,
  loginUser,
  authenticateToken,
  getAllUsers,
  type RegisterRequest,
  type LoginRequest
} from '../services/auth';

// 用户注册接口
export async function handleRegister(req: Request): Promise<Response> {
  try {
    const body = await req.json() as RegisterRequest;
    
    // 验证必填字段
    if (!body.username || !body.email || !body.password) {
      return Response.json({
        success: false,
        message: '用户名、邮箱和密码都是必填项'
      }, { status: 400 });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(body.email)) {
      return Response.json({
        success: false,
        message: '邮箱格式不正确'
      }, { status: 400 });
    }

    // 验证密码长度
    if (body.password.length < 6) {
      return Response.json({
        success: false,
        message: '密码长度至少6位'
      }, { status: 400 });
    }

    const result = await registerUser(body);
    
    if (result.success) {
      return Response.json({
        success: true,
        message: result.message,
        data: {
          user: result.user
        }
      });
    } else {
      return Response.json({
        success: false,
        message: result.message
      }, { status: 400 });
    }
  } catch (error) {
    console.error('注册接口错误:', error);
    return Response.json({
      success: false,
      message: '服务器内部错误'
    }, { status: 500 });
  }
}

// 用户登录接口
export async function handleLogin(req: Request): Promise<Response> {
  try {
    const body = await req.json() as LoginRequest;
    
    // 验证必填字段
    if (!body.username || !body.password) {
      return Response.json({
        success: false,
        message: '用户名和密码都是必填项'
      }, { status: 400 });
    }

    const result = await loginUser(body);
    
    if (result.success) {
      return Response.json({
        success: true,
        message: result.message,
        data: {
          token: result.token,
          user: result.user
        }
      });
    } else {
      return Response.json({
        success: false,
        message: result.message
      }, { status: 401 });
    }
  } catch (error) {
    console.error('登录接口错误:', error);
    return Response.json({
      success: false,
      message: '服务器内部错误'
    }, { status: 500 });
  }
}

// 获取当前用户信息接口
export function handleGetProfile(req: Request): Response {
  const authResult = authenticateToken(req);
  
  if (!authResult.isValid) {
    return Response.json({
      success: false,
      message: authResult.error
    }, { status: 401 });
  }

  return Response.json({
    success: true,
    message: '获取用户信息成功',
    data: {
      user: authResult.user
    }
  });
}

// 获取所有用户接口（管理员功能）
export function handleGetAllUsers(req: Request): Response {
  const authResult = authenticateToken(req);
  
  if (!authResult.isValid) {
    return Response.json({
      success: false,
      message: authResult.error
    }, { status: 401 });
  }

  // 这里可以添加管理员权限检查
  // 简单示例：只有 admin 用户可以查看所有用户
  if (authResult.user?.username !== 'admin') {
    return Response.json({
      success: false,
      message: '权限不足'
    }, { status: 403 });
  }

  const users = getAllUsers();
  
  return Response.json({
    success: true,
    message: '获取用户列表成功',
    data: {
      users
    }
  });
}

// 验证 Token 接口
export function handleVerifyToken(req: Request): Response {
  const authResult = authenticateToken(req);
  
  if (!authResult.isValid) {
    return Response.json({
      success: false,
      message: authResult.error
    }, { status: 401 });
  }

  return Response.json({
    success: true,
    message: 'Token 验证成功',
    data: {
      user: authResult.user
    }
  });
}

// 中间件：保护需要认证的路由
export function requireAuth(handler: (req: Request) => Response | Promise<Response>) {
  return async (req: Request): Promise<Response> => {
    const authResult = authenticateToken(req);
    
    if (!authResult.isValid) {
      return Response.json({
        success: false,
        message: authResult.error
      }, { status: 401 });
    }

    // 将用户信息添加到请求对象中（通过自定义属性）
    (req as any).user = authResult.user;
    
    return handler(req);
  };
}
